package pixelradar.forge;

import com.mojang.realmsclient.RealmsMainScreen;
import com.mojang.realmsclient.dto.RealmsServer;
import com.mojang.realmsclient.gui.ChatFormatting;
import com.mojang.realmsclient.gui.screens.RealmsConfigureWorldScreen;
import com.mojang.realmsclient.gui.screens.RealmsLongRunningMcoTaskScreen;
import com.pixelmonmod.pixelmon.api.pokemon.Pokemon;
import com.pixelmonmod.pixelmon.entities.pixelmon.EntityPixelmon;
import net.minecraft.client.gui.GuiGameOver;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiScreenRealmsProxy;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.realms.RealmsScreen;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.client.event.RenderGameOverlayEvent.Post;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteract;
import net.minecraftforge.event.world.ChunkEvent.Load;
import net.minecraftforge.event.world.ChunkEvent.Unload;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.reflect.FieldUtils;
import pixelradar.Mw;
import pixelradar.config.Config;
import pixelradar.overlay.OverlaySlime;
import pixelradar.util.Logging;
import pixelradar.util.Reference;
import pixelradar.util.Utils;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class EventHandler {
    Mw mw;

    public EventHandler(Mw mw) {
        this.mw = mw;
    }

    @SubscribeEvent
    public void eventChunkLoad(Load event) {
        if (event.getWorld().isRemote) {
            this.mw.onChunkLoad(event.getChunk());
        }

    }

    @SubscribeEvent
    public void eventChunkUnload(Unload event) {
        if (event.getWorld().isRemote) {
            this.mw.onChunkUnload(event.getChunk());
        }

    }

    @SubscribeEvent
    public void onClientChat(ClientChatReceivedEvent event) {
        if (!OverlaySlime.seedFound && OverlaySlime.seedAsked) {
            try {
                if (event.getMessage() instanceof TextComponentTranslation) {
                    TextComponentTranslation component = (TextComponentTranslation) event.getMessage();
                    if ("commands.seed.success".equals(component.getKey())) {
                        Long lSeed;
                        if (component.getFormatArgs()[0] instanceof Long) {
                            lSeed = (Long) component.getFormatArgs()[0];
                        } else {
                            lSeed = Long.parseLong((String) component.getFormatArgs()[0]);
                        }

                        OverlaySlime.setSeed(lSeed);
                        event.setCanceled(true);
                    }
                } else if (event.getMessage() instanceof TextComponentString) {
                    TextComponentString component = (TextComponentString) event.getMessage();
                    String msg = component.getUnformattedText();
                    if (msg.startsWith("Seed: ")) {
                        OverlaySlime.setSeed(Long.parseLong(msg.substring(6)));
                        event.setCanceled(true);
                    }
                }
            } catch (Exception var4) {
                Logging.logError("Something went wrong getting the seed. %s", var4.toString());
            }

        }
    }

    @SubscribeEvent
    public void renderMap(Post event) {
        if (event.getType() == ElementType.HOTBAR) {
            Mw.getInstance().onTick();
        }

    }

    @SubscribeEvent
    public void onTextureStitchEventPost(net.minecraftforge.client.event.TextureStitchEvent.Post event) {
        if (Config.reloadColours) {
            Logging.logInfo("Skipping the first generation of blockcolours, models are not loaded yet", (Object[]) null);
        } else {
            this.mw.reloadBlockColours();
        }

    }

    @SubscribeEvent
    public void renderWorldLastEvent(RenderWorldLastEvent event) {
        if (Mw.getInstance().ready) {
            Mw.getInstance().markerManager.drawMarkersWorld(event.getPartialTicks());
        }

    }

    @SideOnly(Side.CLIENT)
    @SubscribeEvent
    public void onPlayerInteractEvent(EntityInteract event) {
        if (event.getTarget() instanceof EntityPixelmon && event.getHand() == EnumHand.MAIN_HAND && event.getItemStack().isEmpty()) {
            try {
                EntityPixelmon entity = (EntityPixelmon) event.getTarget();
                String name = entity.getName();
                String localizedName = entity.getLocalizedName();
                Pokemon pokemon = entity.getPokemonData();
                boolean isShiny = pokemon.isShiny();
                String form = pokemon.getFormEnum().getLocalizedName();
                String extra = "";
                int level;
                if (entity.isBossPokemon()) {
                    level = entity.getBossMode().getExtraLevels();
                    extra = I18n.format("mw.msg.status.boss");
                } else {
                    level = pokemon.getLevel();
                    if (Reference.LEGENDARIES.contains(name)) {
                        extra = I18n.format("mw.finder.msg.legendary");
                    } else if (Reference.ULTRA_BEASTS.contains(name)) {
                        extra = I18n.format("mw.finder.msg.ultra_beast");
                    } else if (Reference.DITTOS.contains(name)) {
                        extra = I18n.format("mw.finder.msg.ditto");
                    }
                }

                String owner = ChatFormatting.ITALIC + I18n.format("mw.msg.status.owner.wild");
                if (entity.hasOwner()) {
                    owner = Optional.of(Objects.requireNonNull(entity.getOwner()).getName()).orElse(I18n.format("mw.msg.status.owner.someone"));
                }

                EntityPlayer player = event.getEntityPlayer();
                player.sendStatusMessage(new TextComponentString(""), false);
                player.sendMessage(new TextComponentString(Reference.CHAT_BRANDING));
                player.sendStatusMessage(new TextComponentString(ChatFormatting.GREEN + "" + ChatFormatting.BOLD + localizedName + ChatFormatting.RESET + (isShiny ? " (" + ChatFormatting.GREEN + I18n.format("mw.finder.msg.shiny") + ChatFormatting.RESET + ")" : "") + ChatFormatting.ITALIC + " " + ChatFormatting.DARK_AQUA + extra), false);
                player.sendStatusMessage(new TextComponentString(ChatFormatting.GREEN + I18n.format("mw.msg.status.level") + ": " + ChatFormatting.RESET + (entity.isBossPokemon() ? I18n.format("mw.msg.status.boss.extralevels") + " " : "") + level), false);
                player.sendStatusMessage(new TextComponentString(ChatFormatting.GREEN + I18n.format("mw.msg.status.owner") + ": " + ChatFormatting.RESET + owner), false);
                player.sendStatusMessage(new TextComponentString(ChatFormatting.GREEN + I18n.format("mw.msg.status.form") + ": " + ChatFormatting.RESET + form), false);
                player.sendStatusMessage(new TextComponentString(ChatFormatting.GREEN + I18n.format("mw.msg.status.growth") + ": " + ChatFormatting.RESET + entity.getPokemonData().getGrowth().getLocalizedName()), false);
                player.sendStatusMessage(new TextComponentString(""), false);
            } catch (Exception var12) {
                var12.printStackTrace();
            }
        }

    }

    @SubscribeEvent
    public void onGuiOpenEvent(GuiOpenEvent event) {
        GuiScreen guiScreen = event.getGui();
        if (guiScreen instanceof GuiMainMenu && Config.reloadColours) {
            this.mw.reloadBlockColours();
            Config.reloadColours = false;
        } else if (guiScreen instanceof GuiGameOver) {
            this.mw.onPlayerDeath();
        } else if (guiScreen instanceof GuiScreenRealmsProxy) {
            try {
                RealmsScreen proxy = ((GuiScreenRealmsProxy) guiScreen).getProxy();
                RealmsMainScreen parrent = null;
                if (proxy instanceof RealmsLongRunningMcoTaskScreen || proxy instanceof RealmsConfigureWorldScreen) {
                    Object obj = FieldUtils.readField(proxy, "lastScreen", true);
                    if (obj instanceof RealmsMainScreen) {
                        parrent = (RealmsMainScreen) obj;
                    }

                    if (parrent != null) {
                        long id = (Long) FieldUtils.readField(parrent, "selectedServerId", true);
                        if (id > 0L) {
                            List<Object> list = Utils.castList(FieldUtils.readField(parrent, "realmsServers", true), Object.class);

                            RealmsServer server;
                            for (Iterator var9 = list.iterator(); var9.hasNext(); Utils.RealmsWorldName = server.owner + "_" + server.getName()) {
                                Object item = var9.next();
                                server = (RealmsServer) item;
                            }
                        }
                    }
                }
            } catch (IllegalAccessException var12) {
                Pokeradar.logger.error(var12.getMessage());
            }
        }

    }
}
